package com.px.auth.security;

import com.px.common.core.RespCode;
import com.px.common.core.Response;
import com.px.common.util.JsonUtil;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


public class AjaxAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    public void onAuthenticationFailure(
            HttpServletRequest request,
            HttpServletResponse response,
            AuthenticationException exception) throws IOException {

        response.setStatus(HttpStatus.OK.value());
        response.setContentType("application/json; charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        Response error;
        if (exception instanceof DisabledException) {
            error = Response.fail(RespCode.ACCOUNT_DISABLED, exception.getMessage());
        } else if (exception instanceof BadCredentialsException) {
            error = Response.fail(RespCode.BAD_CREDENTIAL, exception.getMessage());
        } else {
            error = Response.fail(RespCode.FAIL, exception.getMessage());
        }

        response.getWriter().println(JsonUtil.toJson(error));
        response.getWriter().flush();
    }
}
